package com.walkline.screen;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.HttpConnection;

import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.system.Application;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;

import com.walkline.util.Enumerations.RefreshActions;
import com.walkline.util.Function;
import com.walkline.util.network.MyConnectionFactory;
import com.walkline.zhihu.ZhihuException;
import com.walkline.zhihu.ZhihuSDK;
import com.walkline.zhihu.inf.DailyStories;
import com.walkline.zhihu.inf.HotStories;
import com.walkline.zhihu.inf.SectionStories;
import com.walkline.zhihu.inf.Sections;
import com.walkline.zhihu.inf.StoryDetails;
import com.walkline.zhihu.inf.ThemeStories;
import com.walkline.zhihu.inf.Themes;

public class RefreshStoriesScreen extends PopupScreen
{
	Thread thread=null;
	ZhihuSDK _zhihu;
	String _date;
	DailyStories _dailyStories;
	HotStories _hotStories;
	StoryDetails _storyDetails;
	Sections _sections;
	SectionStories _sectionStories;
	Themes _themes;
	ThemeStories _themeStories;

	public RefreshStoriesScreen(ZhihuSDK zhihu, String date, int action)
	{
		super(new VerticalFieldManager());

		_zhihu = zhihu;
		_date = date;

		add(new LabelField("Please wait....", Field.FIELD_HCENTER));

		switch (action)
		{
			case RefreshActions.DAILYSTORIES:
				thread = new Thread(new DailyStoriesRunnable());
				break;
			case RefreshActions.STORYDETAILS:
				thread = new Thread(new StoryDetailsRunnable());
				break;
			case RefreshActions.SECTIONSTORYDETAILS:
				thread = new Thread(new SectionStoryDetailsRunnable());
				break;
			case RefreshActions.HOTSTORIES:
				thread = new Thread(new HotStoriesRunnable());
				break;
			case RefreshActions.SECTIONS:
				thread = new Thread(new SectionsRunnable());
				break;
			case RefreshActions.SECTIONSTORIES:
				thread = new Thread(new SectionDetailsRunnable());
				break;
			case RefreshActions.THEMES:
				thread = new Thread(new ThemesRunnable());
				break;
			case RefreshActions.THEMESTORIES:
				thread = new Thread(new ThemeDetailsRunnable());
				break;
		}

		thread.start();
	}

	class HotStoriesRunnable implements Runnable
	{
		public void run()
		{
			try {
				_hotStories = _zhihu.getHotStories();

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	class DailyStoriesRunnable implements Runnable
	{
		public void run()
		{
			try
			{
				_dailyStories = _zhihu.getDailyStories(_date);

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	class StoryDetailsRunnable implements Runnable
	{
		public void run()
		{
			try
			{
				_storyDetails = _zhihu.getStoryDetails(_date);
				if (_storyDetails != null)
				{
					if (!_storyDetails.getImage().equalsIgnoreCase(""))
					{
						MyConnectionFactory cf = new MyConnectionFactory();
		                ConnectionDescriptor descriptor = cf.getConnection(_storyDetails.getImage());

		                if (descriptor == null) {return;}

		                HttpConnection httpConnection = (HttpConnection) descriptor.getConnection();
		                InputStream inputStream = null;

						try {
							inputStream = httpConnection.openInputStream();

							if (inputStream.available() > 0)
							{
								byte[] data = IOUtilities.streamToBytes(inputStream);

								if (data.length == httpConnection.getLength()) {_storyDetails.setImageData(data);}
							}

							inputStream.close();
							httpConnection.close();
						} catch (IOException e) {}
					}
				}

				Application.getApplication().invokeLater(new Runnable() {public void run() {onClose();}});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	class SectionStoryDetailsRunnable implements Runnable
	{
		public void run()
		{
			try
			{
				_storyDetails = _zhihu.getSectionStoryDetails(_date);
				if (_storyDetails != null)
				{
					if (!_storyDetails.getImage().equalsIgnoreCase(""))
					{
						MyConnectionFactory cf = new MyConnectionFactory();
		                ConnectionDescriptor descriptor = cf.getConnection(_storyDetails.getImage());

		                if (descriptor == null) {return;}

		                HttpConnection httpConnection = (HttpConnection) descriptor.getConnection();
		                InputStream inputStream = null;

						try {
							inputStream = httpConnection.openInputStream();

							if (inputStream.available() > 0)
							{
								byte[] data = IOUtilities.streamToBytes(inputStream);

								if (data.length == httpConnection.getLength()) {_storyDetails.setImageData(data);}
							}

							inputStream.close();
							httpConnection.close();
						} catch (IOException e) {}
					}
				}

				Application.getApplication().invokeLater(new Runnable() {public void run() {onClose();}});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	class SectionsRunnable implements Runnable
	{
		public void run()
		{
			try {
				_sections = _zhihu.getSections();

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	class SectionDetailsRunnable implements Runnable
	{
		public void run()
		{
			try {
				_sectionStories = _zhihu.getSectionDetails(_date);

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	class ThemesRunnable implements Runnable
	{
		public void run()
		{
			try {
				_themes = _zhihu.getThemes();

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	class ThemeDetailsRunnable implements Runnable
	{
		public void run()
		{
			try {
				_themeStories = _zhihu.getThemeDetails(_date);

				Application.getApplication().invokeLater(new Runnable()
				{
					public void run() {onClose();}
				});
			} catch (ZhihuException e) {Function.errorDialog(e.toString());}
		}
	}

	public DailyStories getDailyStories() {return _dailyStories;}

	public HotStories getHotStories() {return _hotStories;}

	public StoryDetails getStoryDetails() {return _storyDetails;}

	public Sections getSections() {return _sections;}

	public SectionStories getSectionStories() {return _sectionStories;}

	public Themes getThemes() {return _themes;}

	public ThemeStories getThemeStories() {return _themeStories;}

	public boolean onClose()
	{
		if (thread != null)
		{
			try {
				thread.interrupt();
				thread = null;
			} catch (Exception e) {}
		}

		try {
			UiApplication.getUiApplication().popScreen(this);	
		} catch (Exception e) {}

		return true;
	}

	protected boolean keyChar(char key, int status, int time)
	{
		if (key == Characters.ESCAPE)
		{
			onClose();

			return true;
		}

		return super.keyChar(key, status, time);
	}
} 